import express, { type Request, type Response } from "express";
import cors from "cors";
import helmet from "helmet";
import morgan from "morgan";
import dotenv from "dotenv";
import mongoose from "mongoose";

dotenv.config();

const app = express();

app.use(helmet());
app.use(cors());
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true }));
app.use(morgan("dev"));

// Health check
app.get("/api/health", (_req: Request, res: Response) => {
  res.json({ status: "ok", time: new Date().toISOString() });
});

// Mongo connection (optional in dev)
const mongoUri = process.env.MONGO_URI || "";
const shouldConnectMongo = !!mongoUri;

async function start() {
  try {
    if (shouldConnectMongo) {
      await mongoose.connect(mongoUri);
      // eslint-disable-next-line no-console
      console.log("Mongo connected");
    } else {
      // eslint-disable-next-line no-console
      console.log("MONGO_URI not set, skipping Mongo connection");
    }

    const port = Number(process.env.PORT || 3001);
    app.listen(port, () => {
      // eslint-disable-next-line no-console
      console.log(`Backend listening on http://localhost:${port}`);
    });
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error("Failed to start server", err);
    process.exit(1);
  }
}

void start();
